package com.mall.b2c.plugin.search;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.mall.b2c.domain.goods.GoodsCategoryDomain;
import com.mall.b2c.service.GoodsCategoryService;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.plugin.AutoRegisterPlugin;
/**
 * 商品分类筛选器
 * @author wangzx
 *
 */
public class CategorySearchFilter extends AutoRegisterPlugin implements IGoodsSearchFilter{
	@Resource GoodsCategoryService goodsCategoryService;
	
	@Override
	public void filter(Finder finder, GoodsCategoryDomain cat, String urlFragment) {
		if(StringUtils.isNotBlank(urlFragment) && cat != null){
			finder.append( " and g.goods.goodsCategory.code like CONCAT(:code, '%')");
			finder.setParam("code", cat.getCode());
		}
	}

	@Override
	public List<SearchSelector> createSelectorList(GoodsCategoryDomain cat, String url, 
			String urlFragment, Map<String, String> paramMap, String hql, Finder finder) {
		if(cat == null) {
			throw new NoticeException("当前商品分类不存在!");
		}
		return createSelectors(cat.getChildren());
	}

	private List<SearchSelector> createSelectors(Set<GoodsCategoryDomain> goodsCategoryList) {
		List<SearchSelector> searchSelectors = new ArrayList<SearchSelector>();
		SearchSelector searchSelector = null;
		for(GoodsCategoryDomain goodsCategory : goodsCategoryList) {
			if(goodsCategory.getShowInNav() == Boolean.FALSE) {
				continue;
			}
			searchSelector = new SearchSelector();
			searchSelector.setName(goodsCategory.getName());
			searchSelector.setUrl("/list-cat-"+goodsCategory.getId());
			searchSelectors.add(searchSelector);
		}
		return searchSelectors;
	}

	@Override
	public String getFilterId() {
		return "cat";
	}

	@Override
	public String getSysId() {
		return "catList";
	}

	@Override
	public String getType() {
		return "goodsSearchFilter";
	}

	@Override
	public String getId() {
		return "categorySearchFilter";
	}

	@Override
	public String getName() {
		return "商品分类筛选器";
	}

	@Override
	public String getVersion() {
		return "1.0";
	}

	@Override
	public String getAuthor() {
		return "wangzx";
	}

	@Override
	public void perform(Object... params) {
		
	}

	@Override
	public void register() {
		
	}
}
